import { defineComponent, ref } from 'vue'
import {
  FormRules,
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NInput,
  NRadio,
  NRadioGroup,
  NSpace
} from 'naive-ui'
import { useColumns } from './use-columns'
import { useTable } from './use-table'
import styles from './index.module.scss'
import { modTableReq } from '@/service/modules/data-manage'

const ModTableTab = defineComponent({
  name: 'ModTableTab',
  props: {
    datasourceId: {
      type: Number,
      required: true
    },
    dbName: {
      type: String,
      required: true
    },
    tableName: {
      type: String,
      required: true
    }
  },
  setup() {
    const {
      state,
      modifyTableEntity,
      getTableDetail,
      getDataTypeOptions,
      onOperationClick
    } = useTable()
    const { fieldColumnsRef, indexColumnsRef } = useColumns(
      state,
      onOperationClick
    )
    const rules: FormRules = {
      ddl: {
        trigger: ['input', 'blur'],
        required: true,
        validator() {
          if (modifyTableEntity.ddl === '') {
            return new Error(window.$t('dataManage.ddlTips'))
          }
        }
      }
    }
    const modTableBtnDisableRef = ref(false)
    return {
      state,
      getTableDetail,
      getDataTypeOptions,
      fieldColumnsRef,
      indexColumnsRef,
      modifyTableEntity,
      rules,
      modTableBtnDisableRef
    }
  },
  created() {
    this.getTableDetail(this.datasourceId, this.dbName, this.tableName)
  },
  methods: {
    addNewField() {
      this.modifyTableEntity.tableInfo.columns.push({
        columnName: 'new_column',
        dataType: this.state.dataTypeOptions[0].value as string,
        args: '',
        isNotNull: false,
        defVal: '',
        isPrimkey: false,
        isPartition: false,
        columnComment: '',
        previewData: '',
        newField: true
      })
    },
    async modTable() {
      this.modTableBtnDisableRef = true
      //将预览数据添加到data请求体上
      if (this.modifyTableEntity.mode === 'visual') {
        const previewData = {}
        this.modifyTableEntity.tableInfo.columns.forEach((item) => {
          previewData[item.columnName] = item.previewData
        })
        this.modifyTableEntity.previewData = JSON.stringify(previewData)
      }
      await modTableReq(this.modifyTableEntity).catch(() => {
        this.modTableBtnDisableRef = false
      })
      this.modTableBtnDisableRef = false
    },
    //判断数据源类型是否支持sql修改
    supportSql(): boolean {
      //目前mysql/hive/oracle支持sql修改
      const supportSqlDs = ['MYSQL', 'HIVE', 'ORACLE']
      if (supportSqlDs.indexOf(this.state.tableDetail?.datasourceType) !== -1) {
        return false
      }
      return true
    }
  },
  render() {
    return (
      <div class={styles.container}>
        <div v-show={!this.state.tableDetail}>
          <div class={styles.baseInfo}>
            <NForm
              rules={this.rules}
              label-placement='left'
              require-mark-placement='right-hanging'
              label-width='auto'
            >
              <NFormItem
                path='mode'
                label={window.$t('dataManage.modTableMode')}
              >
                <NRadioGroup v-model:value={this.modifyTableEntity.mode}>
                  <NRadio value='visual'>
                    {window.$t('dataManage.visual')}
                  </NRadio>
                  <NRadio value='sql' disabled={this.supportSql()}>
                    SQL
                  </NRadio>
                </NRadioGroup>
              </NFormItem>
              <NFormItem
                path='tableName'
                label={window.$t('dataManage.tableName')}
                v-show={this.modifyTableEntity.mode === 'visual'}
              >
                <NInput
                  type='text'
                  v-model:value={this.modifyTableEntity.tableInfo.tableName}
                  disabled={true}
                  style='width:200px'
                  placeholder={window.$t('dataManage.tableNameTips')}
                />
              </NFormItem>
              <NFormItem
                path='tableComment'
                label={window.$t('dataManage.tableComment')}
                v-show={this.modifyTableEntity.mode === 'visual'}
              >
                <NInput
                  type='text'
                  v-model:value={this.modifyTableEntity.tableInfo.tableComment}
                  disabled={true}
                  style='width:200px'
                  placeholder={window.$t('dataManage.tableCommentTips')}
                />
              </NFormItem>
              <NFormItem
                path='numPartitions'
                label={window.$t('dataManage.numPartitions')}
                v-show={
                  this.modifyTableEntity.mode === 'visual' &&
                  this.state.tableDetail?.datasourceType === 'KAFKA'
                }
              >
                <NInput
                  type='text'
                  v-model:value={this.modifyTableEntity.ddl}
                  style='width:80px'
                />
              </NFormItem>
              <NFormItem
                path='ddl'
                label={window.$t('dataManage.modTableDDL')}
                v-show={this.modifyTableEntity.mode === 'sql'}
              >
                <NInput
                  type='textarea'
                  v-model:value={this.modifyTableEntity.ddl}
                  placeholder={window.$t('dataManage.modTableDDL')}
                  style='height:300px'
                />
              </NFormItem>
              <NFormItem
                path='tableComment'
                label={window.$t('dataManage.applyReason')}
              >
                <NInput
                  type='textarea'
                  v-model:value={this.modifyTableEntity.reason}
                />
              </NFormItem>
            </NForm>
          </div>
          <div
            class={styles.fieldInfo}
            v-show={this.modifyTableEntity.mode === 'visual'}
          >
            <NSpace justify='space-between'>
              <h3>{window.$t('dataManage.tableConstruction')}</h3>
              <NButton
                type='info'
                size='small'
                onClick={this.addNewField}
                style='margin-top:16px'
              >
                {window.$t('dataManage.addField')}
              </NButton>
            </NSpace>
            <NDataTable
              row-class-name='items'
              columns={this.fieldColumnsRef.fieldColumns}
              size='small'
              single-line={false}
              data={this.modifyTableEntity.tableInfo.columns}
              loading={this.state.loading}
              scrollX={this.fieldColumnsRef.tableWidth}
            />
          </div>
          <div
            class={styles.indexInfo}
            v-show={this.modifyTableEntity.mode === 'visual'}
          >
            <NSpace justify='space-between'>
              <h3>{window.$t('dataManage.tableIndex')}</h3>
            </NSpace>

            <NDataTable
              row-class-name='items'
              columns={this.indexColumnsRef.indexColumns}
              size='small'
              single-line={false}
              data={this.modifyTableEntity.tableInfo.indexs}
              loading={this.state.loading}
              scrollX={this.indexColumnsRef.tableWidth}
            />
          </div>
          <NSpace justify='center' style='margin-top:10px'>
            <NButton
              type='info'
              onClick={this.modTable}
              disabled={this.modTableBtnDisableRef}
            >
              {window.$t('dataManage.modTable')}
            </NButton>
          </NSpace>
        </div>
        <div v-show={!this.state.tableDetail}>您没有权限查看当前表详情</div>
      </div>
    )
  }
})

export default ModTableTab
